# -*- coding:utf-8 -*-
import json
import os
import uuid
from datetime import datetime, timedelta
import torndb
import requests

import setting

class TmpGiftNotice(object):
    """
    导入20周年礼品给用户

    """

    def __init__(self):

        self.db = torndb.Connection(
            host=setting.mysql_host,
            database=setting.mysql_database,
            user=setting.mysql_user,
            password=setting.mysql_password,
            charset='utf8mb4'
        )

        self.access_token = ""


    def _get_create_tmp_user(self):
        """
        获取获奖人的openid和对应的礼物（商品ID）

        :return:
        """
        return self.db.query("select * from tmp_user")


    def _user_is_exist(self, openid):
        """
        校验该商品名称是否存在，防止重复导入

        :param product_name: 商品名称
        :return:
        """
        return self.db.get("select * from t_wechat where openid=%(openid)s", openid=openid)

    def _get_wechat_user_info(self, openid):
        """
        校验该商品名称是否存在，防止重复导入

        :param product_name: 商品名称
        :return:
        """
        url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={}&openid={}&lang=zh_CN".format(self.access_token, openid)
        res = requests.get(url).json()
        print res
        return res

    def _create_user_info(self, mobile):
        user_id = str(uuid.uuid4()).replace("-", "")
        token = str(uuid.uuid4()).replace("-", "")
        data = {"id": user_id, "token": token, "mobile": mobile}
        self.db.execute("insert into t_user (id, mobile, token, create_date) values (%(id)s,%(mobile)s,%(token)s,now())", **data)
        print "user_id:{}".format(user_id)
        return user_id

    def _upd_wechat(self, openid, user_id):
        self.db.execute("update t_wechat set user_id=%(user_id)s where openid=%(openid)s", openid=openid, user_id=user_id)

    def _create_wechat_user(self, params):
        """
        将商品插入t_product表
{
    "subscribe": 1,
    "openid": "oeQDZt041PHGtfLUHyoifxkgBhlo",
    "nickname": "中岳游子",
    "sex": 1,
    "language": "zh_CN",
    "city": "海淀",
    "province": "北京",
    "country": "中国",
    "headimgurl": "http://thirdwx.qlogo.cn/mmopen/ajNVdqHZLLC5YAttcXxFEeNmXoGhze1xjdOzw8zh19eXCibrzcw0nuJyXn1ibwvUqmHZLGogPB5jczOLcmpRnknA/132",
    "subscribe_time": 1526624911,
    "unionid": "oGCG8t_VY2ynZnWvkWPWSDL9cokc",
    "remark": "",
    "groupid": 0,
    "tagid_list": [ ],
    "subscribe_scene": "ADD_SCENE_SEARCH",
    "qr_scene": 0,
    "qr_scene_str": ""
}

        :param params:
        :return:
        """
        params.update({"id": str(uuid.uuid4()).replace("-", "")})
        self.db.execute(
            "insert into t_wechat(id, official_accounts, subscribe,openid,nickname,sex, headimgurl,"
            "city,province,country,unionid,language,"
            "create_date,update_date) "
            "values (%(id)s,1,%(subscribe)s,%(openid)s,%(nickname)s,%(sex)s, %(headimgurl)s,"
            "%(city)s,%(province)s,%(country)s,%(unionid)s,"
            "%(language)s,now(), now())",
            **params)

    def runner(self):

        users = self._get_create_tmp_user()
        for u in users:
            if not self._user_is_exist(u.openid):
                wechat_user = self._get_wechat_user_info(u.openid)
                self._create_wechat_user(wechat_user)
                user_id = self._create_user_info(u.mobile)
                self._upd_wechat(u.openid, user_id)
            else:
                print u"openid:{} is exist!".format(u.openid)


if __name__ == '__main__':
    print "run start : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    tgn = TmpGiftNotice()
    tgn.runner()
    tgn.db.close()
    print "run end : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


